<template>
  <el-dialog
    ref="refDlg"
    :title="formData.id ? '编辑' : '新增'"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="600px"
    @close="closeDialog"
  >
    <div>
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="门店:" prop="shopName">
              <input-with-dialog
                v-model="shop"
                :props="{label:'shopName',value:'shopCode'}"
                :config="shopConfig"
                @change="shopChange"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="所属专区:" prop="belongAreaName">
              <input-with-dialog
                v-model="belongArea"
                :props="{label:'areaName',value:'areaCode'}"
                :config="belongAreaConfig"
                @change="belongAreaChange"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="专区划分:" prop="zoneDivisionCode">
              <el-select
                v-model="formData.zoneDivisionCode"
                placeholder="请选择"
                @change="changeCode"
              >
                <el-option
                  v-for="item in zoneDivisionList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="!detailData.id" :span="24">
            <el-table
              :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
              show-overflow-tooltip
              border
              :data="tableList"
              style="width: 100%"
            >
              <el-table-column prop="areaName" label="专区名称" width="110" />
              <el-table-column prop="areaCode" label="专区编码" width="90" />
              <el-table-column prop="productTotal" label="可陈列数量" width="100">
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.productTotal"
                    placeholder="请输入"
                    @input="data=>{return data==0? scope.row.productTotal=null:scope.row.productTotal=data }"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="enable" label="启用状态" min-width="160">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.enable">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">停用</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column prop="enable" label="操作" min-width="120">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="handleDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col v-else>
            <el-form-item label="可陈列数量:" prop="productTotal">
              <el-input
                v-model.number="formData.productTotal"
                placeholder="请输入"
                @input="data=>{return data==0? formData.productTotal=null:formData.productTotal=data }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" :loading="submiting" type="primary" @click="submitForm(detailData.id?1:0)">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getSpaceList } from '@/api/display/space'
import { saveDisplayTotal } from '@/api/display/displayTotal'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'EditForm',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      submiting: false,
      tableList: [],
      shop: [],
      zoneList: [],
      belongArea: [],
      zoneDivisionList: [],
      shopConfig: {
        title: '门店',
        interfacePath: `/slm-admin/api/v1/displayHistoryData/getShopList`,
        method: 'get',
        setting: [
          {
            prop: 'shopCode',
            title: '编码'
          },
          {
            prop: 'shopName',
            title: '名称'
          }
        ]
      },
      belongAreaConfig: {
        title: '所属专区',
        interfacePath: `/slm-admin/api/v1/displayAreaCategory/page`,
        setting: [
          {
            prop: 'areaCode',
            title: '编码'
          },
          {
            prop: 'areaName',
            title: '名称'
          }
        ]
      },
      formData: { shopName: '',
        shopCode: '', enable: 1,
        belongAreaName: '', belongAreaCode: '', zoneDivisionCode: '', productTotal: undefined
      },
      formRules: {
        shopName: [{ required: true, message: '请选择', trigger: 'change' }],
        belongAreaName: [{ required: true, message: '请选择', trigger: 'change' }],
        zoneDivisionCode: [{ required: true, message: '请选择', trigger: 'change' }],
        productTotal: [{ required: true, message: '请填写', trigger: 'blur' }]
      }
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    const data = this.detailData
    if (data && data.id) {
      const { id, shopName, shopCode, enable = 1, belongAreaName, belongAreaCode, zoneDivisionCode, zoneDivisionName, productTotal } = data
      this.formData = { id, shopName, shopCode, enable, belongAreaName, belongAreaCode, zoneDivisionCode, zoneDivisionName, productTotal }
      this.shop = [{ label: this.formData.shopName, value: this.formData.shopCode }]
      this.belongArea = [{ label: this.formData.belongAreaName, value: this.formData.belongAreaCode }]
    }
    const { ZONE_DIVISION } = await getDictByPatchType(['ZONE_DIVISION'])
    this.zoneDivisionList = ZONE_DIVISION // 专区划分
  },

  methods: {
    belongAreaChange(data) {
      if (data && data.length > 0) {
        this.$set(this.formData, 'belongAreaName', data[0].areaName)
        this.$set(this.formData, 'belongAreaCode', data[0].areaCode)
      } else {
        this.$set(this.formData, 'belongAreaName', '')
        this.$set(this.formData, 'belongAreaCode', '')
      }
    },
    shopChange(data) {
      if (data && data.length > 0) {
        this.$set(this.formData, 'shopName', data[0].shopName)
        this.$set(this.formData, 'shopCode', data[0].shopCode)
      } else {
        this.$set(this.formData, 'shopName', '')
        this.$set(this.formData, 'shopCode', '')
      }
    },
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    changeCode(data) {
      if (this.zoneList.length === 0) {
        getSpaceList().then(res => {
          this.zoneList = res.data
          if (res.success) this.tableList = this.zoneList.filter(v => v.superCategoryCode === data)
        })
      } else {
        this.tableList = this.zoneList.filter(v => v.superCategoryCode === data)
      }
    },
    clearForm(done) {
      this.formData = {
        shopName: '',
        shopCode: '', enable: 1,
        belongAreaName: '', belongAreaCode: '', zoneDivisionCode: '', productTotal: undefined
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    handleDelete(index) {
      this.tableList.splice(index, 1)
    },
    // 提交表单处理
    /**
     * type,1为编辑，0为新增
     */
    submitForm(type) {
      if (this.submiting) return
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          // return
          if (type === 1) {
            if (!this.formData.productTotal || this.formData.productTotal === '0') {
              this.$message.warning('未填写的陈列数')
              return
            }
            this.submiting = true
            saveDisplayTotal(this.formData, 1).then(res => {
              this.submiting = false
              this.closeDialog()
              this.$emit('success')
            }).catch(() => {
              this.submiting = false
            })
          } else {
            const temp = this.tableList.filter(v => !v.productTotal)
            if (temp.length > 0) {
              this.$message.warning('存在未填写的陈列数')
              return
            }
            this.submiting = true
            this.tableList.forEach(v => {
              const i = {
                shopName: this.formData.shopName,
                shopCode: this.formData.shopCode,
                enable: v.enable || 1,
                belongAreaName: v.areaName,
                belongAreaCode: v.areaCode,
                zoneDivisionCode: this.formData.zoneDivisionCode,
                productTotal: v.productTotal || 0
              }
              saveDisplayTotal(i, 0).then(res => {
                this.submiting = false
                this.closeDialog()
                this.$emit('success')
              }).catch(() => {
                this.submiting = false
              })
            })
          }

          this.$message({
            message: '操作成功',
            type: 'success'
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
// 禁用颜色
/deep/.el-radio__input.is-disabled.is-checked .el-radio__inner{
 background-color: #9d9fa1;
}
/deep/.el-textarea.is-disabled .el-textarea__inner{
  color: #606266;
}
/deep/.el-input.is-disabled .el-input__inner {
  color: #606266;
}
</style>
